package query_handler

import (
	"crypto/sha256"
	"encoding/hex"
	"file-cleaner/internal/file_cleaner/cache"
	"file-cleaner/internal/file_cleaner/file_info"
	v1log "github.com/ClessLi/component-base/pkg/log/v1"
	"os"
	"time"
)

type QueryHandler interface {
	doHandle(info *file_info.FileInfo) bool
}

type QueryByATimeImpl struct {
	AfterTime  time.Time
	BeforeTime time.Time
}

type QueryByCTimeImpl struct {
	AfterTime  time.Time
	BeforeTime time.Time
}

type QueryByMTimeImpl struct {
	AfterTime  time.Time
	BeforeTime time.Time
}

type QueryHashImpl struct {
	fc cache.BytesCache
}

func NewQueryHashImpl() QueryHandler {
	return &QueryHashImpl{fc: cache.NewBytesCache(1024)}
}

func (h QueryHashImpl) doHandle(info *file_info.FileInfo) bool {
	var err error
	bfile := h.fc.Get()
	defer h.fc.Release(bfile)
	*bfile, err = os.ReadFile(info.Path())
	if err != nil {
		v1log.Error(err.Error())
		return false
	}
	info.SetHash(h.sha256Hash(*bfile))
	return true
}

func (h QueryHashImpl) sha256Hash(data []byte) string {
	m := sha256.New()
	m.Write(data)
	return hex.EncodeToString(m.Sum(nil))
}

type QueryForDeleteOnlyImpl struct {
}

func (d QueryForDeleteOnlyImpl) doHandle(info *file_info.FileInfo) bool {
	err := info.SetTag(file_info.OnlyDelete)
	if err != nil {
		v1log.Errorf("Failed to set tag for file: %v, cased by: %v", info.Path(), err)
		return false
	}
	info.SetHash("OnlyDelete")
	return true
}
